package com.wangxiaoxuan.seckill.config;

import com.wangxiaoxuan.seckill.Util.CookieUtil;
import com.wangxiaoxuan.seckill.pojo.User;
import com.wangxiaoxuan.seckill.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王小轩
 * @version 1.0
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserService userService;
    @Override
    public boolean supportsParameter(MethodParameter parameter) {//做出条件判断；返回true才会执行下面的 resolveArgument
       //得到传入参数的类型
        Class<?> clazz = parameter.getParameterType();
        //如果是user类型，执行下面方法完成校验
        return clazz== User.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        //先通过webRequest拿到request,response
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        //再通过CookieUtil拿到cookie里的值
        String ticket = CookieUtil.getCookieValue(request, "userTicket");
        //判断
        if(StringUtils.isEmpty(ticket)){
            return null;
        }

        return userService.getUserByCookie(ticket,request,response);
    }
}
